package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    XcMenuMapper xcMenuMapper;

    /**
     * 查询数据库
     *
     * @param s AuthParamsDto类型的json数据
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //将json数据转换为AuthParamsDto对象
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("认证请求格式不对");
        }

        //认证类型 ，有password，wx
        String authType = authParamsDto.getAuthType();

        //根据不同的认证类型，取出不同的bean
        String beanName = authType + "_authservice";
        AuthService bean = applicationContext.getBean(beanName, AuthService.class);

        //调用统一的excute方法，完成认证
        XcUserExt user = bean.execute(authParamsDto);

        //根据这个对象生成令牌
        return getUserPrincipal(user);

//        //查询数据库---通过username账号
//        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, authParamsDto.getUsername()));
//
//        //查询用户不存在，返回null即可，spring security框架抛出异常用户不存在
//        if (xcUser==null){
//            return null;
//        }

//        //查询到用户存在，拿到正确的密码，最终封装成UserDetails对象给spring security框架返回，由框架进行密码比对
//        String password = xcUser.getPassword();
//        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
//        String[] authorities ={"test"};
//        //将敏感信息置空
//        xcUser.setPassword(null);
//        //将用户信息转JSON
//        String userJson = JSON.toJSONString(xcUser);
//        //创建UserDetails对象,权限信息待实现授权功能时再向UserDetail中加入
//        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
//
//        return userDetails;
    }


    /**
     * @param user 用户id，主键
     * @return com.xuecheng.ucenter.model.po.XcUser 用户信息
     * @description 查询用户信息
     * @author Mr.M
     * @date 2022/9/29 12:19
     */
    private UserDetails getUserPrincipal(XcUserExt user) {

        //权限
        String[] authorities = {"p1"};

        //根据用户id查询用户的权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        List<String> permissions = new ArrayList<>();
        if (xcMenus.size() > 0) {
            xcMenus.forEach(xcMenu -> {
                //拿到用户拥有的权限标识符
                permissions.add(xcMenu.getCode());
            });
        }
        //将permissions转换为数组
        authorities = permissions.toArray(new String[0]);
        String password = user.getPassword();

        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String jsonString = JSON.toJSONString(user);
        //创建UserDetails对象
        UserDetails userDetails = User.withUsername(jsonString).password(password).authorities(authorities).build();

        return userDetails;
    }
}
